package cn.easyplatform.studio.web.editors.admin;

import cn.easyplatform.entities.beans.project.DeviceMapBean;
import cn.easyplatform.entities.beans.project.PortletBean;
import cn.easyplatform.entities.beans.project.ProjectBean;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.identity.*;
import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.utils.*;
import cn.easyplatform.studio.vos.TemplateVo;
import cn.easyplatform.studio.web.editors.AbstractPanelEditor;
import cn.easyplatform.studio.web.editors.Editor;
import cn.easyplatform.studio.web.editors.EditorCallback;
import cn.easyplatform.studio.web.editors.Savable;
import cn.easyplatform.studio.web.editors.support.CodeFormatter;
import cn.easyplatform.studio.web.editors.support.ZulXsdUtil;
import cn.easyplatform.studio.web.layout.WorkbenchController;
import cn.easyplatform.studio.web.views.impl.AbstractView;
import cn.easyplatform.type.DeviceType;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.commons.io.IOUtils;
import org.apache.tika.metadata.Office;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.*;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author Zeta
 * @Version 1.0
 */
public class TemplateCfgEditor extends AbstractPanelEditor implements Savable {

    public TemplateCfgEditor(WorkbenchController workbench, String id) {
        super(workbench, id);
    }

    private boolean updateFlag;
    private boolean loginSaveFlag = false;
    private boolean mainSaveFlag = false;
    private String portlet_type;
    private String loginXml = null;
    private String mainXml = null;
    private int index;
    private String projectName = Contexts.getProject().getId();
    private String msg;

    private Tree tree;
    private Iframe laptopLoginPage;
    private Iframe laptopMainPage;
    private Iframe mobileLoginPage;
    private Iframe mobileMainPage;
    private Textbox name;
    private Textbox desc;
    private Textbox query;
    private Label prompt;
    private Button portlet_create;
    private Button imageImport_laptop_login;
    private Button chooseTemp_laptop_login;
    private Button fileImport_laptop_login;
    private Button imageImport_laptop_main;
    private Button chooseTemp_laptop_main;
    private Button fileImport_laptop_main;
    private Button edit_laptop_login;
    private Button edit_laptop_main;
    private Button imageImport_mobile_login;
    private Button chooseTemp_mobile_login;
    private Button fileImport_mobile_login;
    private Button imageImport_mobile_main;
    private Button chooseTemp_mobile_main;
    private Button fileImport_mobile_main;
    private Button edit_mobile_login;
    private Button edit_mobile_main;
    private Button template_save;
    private Div laptop_div;
    private Div mobile_div;
    private Div mobileLoginDiv;
    private Div mobileMainDiv;
    private Image loginBgImage;
    private Image mainBgImage;
    private Label editMsg;
    private TemplateUtil.TemplateType template_login;
    private TemplateUtil.TemplateType template_main;

    @Override
    public void create(Object... args) {
        Idspace is = createPanel(Labels.getLabel("menu.the.template.configuration"), "~./images/dictionary.png",
                "~./include/admin/templatecfgs.zul");

        laptopLoginPage = (Iframe) is.getFellow("page_iframe_laptop_loginPage");
        laptopMainPage = (Iframe) is.getFellow("page_iframe_laptop_mainPage");
        mobileLoginPage = (Iframe) is.getFellow("page_iframe_mobile_loginPage");
        mobileMainPage = (Iframe) is.getFellow("page_iframe_mobile_mainPage");
        name = (Textbox) is.getFellow("page_textbox_name");
        name.addEventListener(Events.ON_CHANGE, this);
        desc = (Textbox) is.getFellow("page_textbox_desc");
        query = (Textbox) is.getFellow("page_textbox_query");
        prompt = (Label) is.getFellow("page_label_prompt");
        editMsg = (Label) is.getFellow("page_label_edit_msg");


        tree = (Tree) is.getFellow("page_tree_portlet");
        tree.addEventListener(Events.ON_SELECT, this);
        portlet_create = (Button) is.getFellow("page_button_create");
        portlet_create.addEventListener(Events.ON_CLICK, this);
        template_save = (Button) is.getFellow("page_button_template_save");
        template_save.addEventListener(Events.ON_CLICK, this);

        imageImport_laptop_login = (Button) is.getFellow("page_toolbarbutton_laptop_imageImport_login");
        imageImport_laptop_login.addEventListener(Events.ON_CLICK, this);
        chooseTemp_laptop_login = (Button) is.getFellow("page_toolbarbutton_laptop_chooseTemp_login");
        chooseTemp_laptop_login.addEventListener(Events.ON_CLICK, this);
        fileImport_laptop_login = (Button) is.getFellow("page_toolbarbutton_laptop_fileImport_login");
        fileImport_laptop_login.addEventListener(Events.ON_UPLOAD, this);
        imageImport_laptop_main = (Button) is.getFellow("page_toolbarbutton_laptop_imageImport_main");
        imageImport_laptop_main.addEventListener(Events.ON_CLICK, this);
        chooseTemp_laptop_main = (Button) is.getFellow("page_toolbarbutton_laptop_chooseTemp_main");
        chooseTemp_laptop_main.addEventListener(Events.ON_CLICK, this);
        fileImport_laptop_main = (Button) is.getFellow("page_toolbarbutton_laptop_fileImport_main");
        fileImport_laptop_main.addEventListener(Events.ON_UPLOAD, this);
        edit_laptop_login = (Button) is.getFellow("page_toolbarbutton_laptop_edit_login");
        edit_laptop_login.addEventListener(Events.ON_CLICK, this);
        edit_laptop_main = (Button) is.getFellow("page_toolbarbutton_laptop_edit_main");
        edit_laptop_main.addEventListener(Events.ON_CLICK, this);
        imageImport_mobile_login = (Button) is.getFellow("page_toolbarbutton_mobile_imageImport_login");
        imageImport_mobile_login.addEventListener(Events.ON_CLICK, this);
        chooseTemp_mobile_login = (Button) is.getFellow("page_toolbarbutton_mobile_chooseTemp_login");
        chooseTemp_mobile_login.addEventListener(Events.ON_CLICK, this);
        fileImport_mobile_login = (Button) is.getFellow("page_toolbarbutton_mobile_fileImport_login");
        fileImport_mobile_login.addEventListener(Events.ON_UPLOAD, this);
        imageImport_mobile_main = (Button) is.getFellow("page_toolbarbutton_mobile_imageImport_main");
        imageImport_mobile_main.addEventListener(Events.ON_CLICK, this);
        chooseTemp_mobile_main = (Button) is.getFellow("page_toolbarbutton_mobile_chooseTemp_main");
        chooseTemp_mobile_main.addEventListener(Events.ON_CLICK, this);
        fileImport_mobile_main = (Button) is.getFellow("page_toolbarbutton_mobile_fileImport_main");
        fileImport_mobile_main.addEventListener(Events.ON_UPLOAD, this);
        edit_mobile_login = (Button) is.getFellow("page_toolbarbutton_mobile_edit_login");
        edit_mobile_login.addEventListener(Events.ON_CLICK, this);
        edit_mobile_main = (Button) is.getFellow("page_toolbarbutton_mobile_edit_main");
        edit_mobile_main.addEventListener(Events.ON_CLICK, this);
        laptop_div = (Div) is.getFellow("page_div_laptop");
        mobile_div = (Div) is.getFellow("page_div_mobile");
        mobileLoginDiv = (Div) is.getFellow("page_div_mobile_canvas_login");
        loginBgImage = (Image) is.getFellow("page_mobile_image_bg_login");
        mobileMainDiv = (Div) is.getFellow("page_div_mobile_canvas_main");
        mainBgImage = (Image) is.getFellow("page_mobile_image_bg_login");


        portlet_type = "laptop";
        template_login = TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN;
        template_main = TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN;
        portletInitialize();
    }


    @Override
    protected void dispatch(Event evt) {
        if (evt.getTarget() == tree) {
            selectedItem();
        }else if (evt.getTarget() == template_save) {
            if (null != name.getValue() && !"".equals(name.getValue())) {
                if (save()) {
                    WebUtils.showSuccess(Labels.getLabel("button.save"));
                } else {
                    WebUtils.showError(Labels.getLabel("message.error", new String[]{Labels.getLabel("button.save")}));
                }
            } else {
                WebUtils.showInfo(Labels.getLabel("admin.project.portlet.name.warning"));
            }
        } else if (evt.getTarget() == portlet_create) {
            onCreate();
        } else if (evt.getTarget() instanceof A) {
            onDelete(evt);
        } else if (evt.getTarget() == chooseTemp_laptop_login) {
            if ("laptop".equals(portlet_type)) {
                template_login = TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN;
            } else {
                template_login = TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_LOGIN;
            }
            AbstractView.createAppPageTemplateView(new EditorCallback<String>() {
                @Override
                public String getValue() {
                    return null;
                }

                @Override
                public void setValue(String value) {
                    loginSaveFlag = true;
                    setContent(value, template_login);
                }

                @Override
                public String getTitle() {
                    return Labels.getLabel("editor.template.image.import");
                }

                @Override
                public Page getPage() {
                    return laptopLoginPage.getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            }, name.getValue(), template_login, evt.getTarget()).doOverlapped();

        } else if (evt.getTarget() == chooseTemp_laptop_main) {

            if ("laptop".equals(portlet_type)) {
                template_main = TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN;
            } else {
                template_main = TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_MAIN;
            }
            AbstractView.createAppPageTemplateView(new EditorCallback<String>() {
                @Override
                public String getValue() {
                    return null;
                }

                @Override
                public void setValue(String value) {
                    mainSaveFlag = true;
                    setContent(value, template_main);
                }

                @Override
                public String getTitle() {
                    return Labels.getLabel("editor.template.image.import");
                }

                @Override
                public Page getPage() {
                    return laptopLoginPage.getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            }, name.getValue(), template_main, evt.getTarget()).doOverlapped();

        } else if (evt.getTarget() == imageImport_laptop_login) {

            imageImport(evt, template_login);

        } else if (evt.getTarget() == imageImport_laptop_main) {

            imageImport(evt, template_main);

        } else if (evt.getTarget() == edit_laptop_login) {

            updateFlag = true;
            AbstractView.createAppPageEditorView(new EditorCallback<String>() {
                @Override
                public String getValue() {
                    return null;
                }

                @Override
                public void setValue(String value) {
                    updateFlag = false;
                    loginXml =updateXml(updateFlag,value,name.getValue(),template_login);
                    redraw(loginXml, laptopLoginPage, "login");
                }

                @Override
                public String getTitle() {
                    return Labels.getLabel("editor.template.image.import");
                }

                @Override
                public Page getPage() {
                    return laptopLoginPage.getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            }, updateXml(updateFlag,loginXml,name.getValue(),template_login), evt.getTarget()).doOverlapped();

        } else if (evt.getTarget() == edit_laptop_main) {

            updateFlag = true;
            AbstractView.createAppPageEditorView(new EditorCallback<String>() {
                @Override
                public String getValue() {
                    return null;
                }

                @Override
                public void setValue(String value) {
                    updateFlag = false;
                    mainXml =updateXml(updateFlag,value,name.getValue(),template_main);
                    redraw(mainXml, laptopMainPage, "main");
                }

                @Override
                public String getTitle() {
                    return Labels.getLabel("editor.template.image.import");
                }

                @Override
                public Page getPage() {
                    return laptopLoginPage.getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            },updateXml(updateFlag,mainXml,name.getValue(),template_main), evt.getTarget()).doOverlapped();
        } else if (evt.getTarget() == fileImport_laptop_login) {
            setfileImport(evt);
        } else if (evt.getTarget() == fileImport_laptop_main) {
            setfileImport(evt);
        } else if (evt.getTarget() == chooseTemp_mobile_login) {
            if ("laptop".equals(portlet_type)) {
                template_login = TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN;
            } else {
                template_login = TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_LOGIN;
            }

            AbstractView.createAppPageTemplateView(new EditorCallback<String>() {
                @Override
                public String getValue() {
                    return null;
                }

                @Override
                public void setValue(String value) {
                    loginSaveFlag = true;
                    setContent(value, template_login);
                }

                @Override
                public String getTitle() {
                    return Labels.getLabel("editor.template.image.import");
                }

                @Override
                public Page getPage() {
                    return mobileLoginPage.getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            }, name.getValue(), template_login, evt.getTarget()).doOverlapped();
        } else if (evt.getTarget() == chooseTemp_mobile_main) {
            if ("laptop".equals(portlet_type)) {
                template_main = TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN;
            } else {
                template_main = TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_MAIN;
            }

            AbstractView.createAppPageTemplateView(new EditorCallback<String>() {
                @Override
                public String getValue() {
                    return null;
                }

                @Override
                public void setValue(String value) {
                    mainSaveFlag = true;
                    setContent(value, template_main);
                }

                @Override
                public String getTitle() {
                    return Labels.getLabel("editor.template.image.import");
                }

                @Override
                public Page getPage() {
                    return mobileLoginPage.getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            }, name.getValue(), template_main, evt.getTarget()).doOverlapped();
        } else if (evt.getTarget() == imageImport_mobile_login) {

            imageImport(evt, template_login);

        } else if (evt.getTarget() == imageImport_mobile_main) {

            imageImport(evt, template_main);

        } else if (evt.getTarget() == edit_mobile_login) {

            updateFlag = true;
            AbstractView.createAppPageEditorView(new EditorCallback<String>() {
                @Override
                public String getValue() {
                    return null;
                }

                @Override
                public void setValue(String value) {
                    updateFlag = false;
                    loginXml =updateXml(updateFlag,value,name.getValue(),template_login);
                    redraw(loginXml, mobileLoginPage, "login");
                }

                @Override
                public String getTitle() {
                    return Labels.getLabel("editor.template.image.import");
                }

                @Override
                public Page getPage() {
                    return mobileLoginPage.getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            }, updateXml(updateFlag,loginXml,name.getValue(),template_login), evt.getTarget()).doOverlapped();

        } else if (evt.getTarget() == edit_mobile_main) {

            updateFlag = true;
            AbstractView.createAppPageEditorView(new EditorCallback<String>() {
                @Override
                public String getValue() {
                    return null;
                }

                @Override
                public void setValue(String value) {
                    updateFlag = false;
                    mainXml =updateXml(updateFlag,value,name.getValue(),template_main);
                    redraw(mainXml,mobileMainPage, "main");
                }

                @Override
                public String getTitle() {
                    return Labels.getLabel("editor.template.image.import");
                }

                @Override
                public Page getPage() {
                    return mobileLoginPage.getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            },updateXml(updateFlag,mainXml,name.getValue(),template_main), evt.getTarget()).doOverlapped();

        } else if (evt.getTarget() == fileImport_mobile_login) {
            setfileImport(evt);
        } else if (evt.getTarget() == fileImport_mobile_main) {
            setfileImport(evt);
        } else if (evt.getTarget() instanceof Textbox && evt.getName().equals(Events.ON_CHANGE)){
            for (PortletBean pb : Contexts.getProject().getPortlets()) {
                if (name.getValue().equals(pb.getName())||"default".equals(pb.getName())||"template".equals(pb.getName())) {
                    WebUtils.showInfo(Labels.getLabel("admin.project.portlet.name.repetition"));
                    template_save.setDisabled(true);
                    break;
                }
                template_save.setDisabled(false);
            }

        }
    }

    //门户初始化
    private void portletInitialize() {

        //若无门户，添加门户集合
        ProjectBean project = Contexts.getProject();
        if (project.getPortlets() == null)
            project.setPortlets(new ArrayList<PortletBean>());

        //创建默认门户
        Treeitem ti = new Treeitem();
        ti.setSelectable(false);
        ti.setValue("default");
        Treerow tr = new Treerow();
        tr.appendChild(new Treecell("default"));
        Treecell cell = new Treecell();
        tr.appendChild(cell);
        ti.appendChild(tr);
        Treechildren tc = new Treechildren();
        createFolder("");
        for (DeviceMapBean dv : Contexts.getProject().getDevices()) {
            Treeitem tm = new Treeitem();
            tm.setValue(dv.getType());
            tr = new Treerow();
            Treecell treecell = new Treecell(dv.getType().equals("ajax") ? Labels.getLabel("admin.project.device.ajax") : Labels.getLabel("admin.project.device.phone"));
            treecell.setIconSclass(tm.getValue().equals("ajax") ? "z-icon-laptop h5" : "z-icon-tablet h5");
            treecell.setSpan(3);
            tr.appendChild(treecell);
            tm.appendChild(tr);
            tc.appendChild(tm);
            if("ajax".equals(dv.getType())&&null!=getDevice(dv,template_login)&&null!=getDevice(dv,template_main)){
                loginXml = updateXml(updateFlag,getDevice(dv,template_login),"",template_login);
                mainXml = updateXml(updateFlag,getDevice(dv,template_main),"",template_main);
            }else if("ajax".equals(dv.getType())){
                dv.setLoginId(0);
                dv.setMainId(0);
                loginXml = null;
                mainXml = null;
            }
        }
        ti.appendChild(tc);
        tree.getTreechildren().appendChild(ti);
        name.setValue("default");
        name.setDisabled(true);
        desc.setValue(Labels.getLabel("admin.project.default.portlet"));
        desc.setDisabled(true);
        query.setValue("");
        query.setDisabled(true);

        for (PortletBean pb : Contexts.getProject().getPortlets()){
            createNode(pb);
            createFolder(pb.getName());
        }

        redraw(loginXml, laptopLoginPage, "login");
        redraw(mainXml, laptopMainPage, "main");

    }

    //生成新门户对象
    private void onCreate() {
        portlet_type = "laptop";
        ProjectBean project = Contexts.getProject();
        PortletBean pb = new PortletBean();
        project.getPortlets().add(pb);
        Treeitem ti = createNode(pb);
        ((Treeitem) ti.getLastChild().getFirstChild()).setSelected(true);
        index = Contexts.getProject().getPortlets().indexOf(pb);
        if (laptopLoginPage.getFirstChild() != null)
            laptopLoginPage.getFirstChild().detach();
        if (laptopMainPage.getFirstChild() != null)
            laptopMainPage.getFirstChild().detach();
        if (mobileLoginPage.getFirstChild() != null)
            mobileLoginPage.getFirstChild().detach();
        if (mobileMainPage.getFirstChild() != null)
            mobileMainPage.getFirstChild().detach();
        name.setDisabled(false);
        desc.setDisabled(false);
        query.setDisabled(false);
        prompt.setVisible(true);
        selectedItem();
    }

    //创建门户树结构
    private Treeitem createNode(PortletBean pv) {
        Treeitem ti = new Treeitem();
        ti.setSelectable(false);
        ti.setValue(pv);
        Treerow tr = new Treerow();
        if (null == pv.getName() || ("").equals(pv.getName())) {
            tr.appendChild(new Treecell(Labels.getLabel("admin.project.new.portlet")));
        } else {
            tr.appendChild(new Treecell(pv.getName()));
        }
        A deleteBtn = new A();
        deleteBtn.setLabel(Labels.getLabel("button.delete"));
        deleteBtn.addEventListener(Events.ON_CLICK, this);
        deleteBtn.setSclass("ml-2");
        deleteBtn.setIconSclass("z-icon-trash");
        Treecell cell = new Treecell();
        cell.appendChild(deleteBtn);
        tr.appendChild(cell);
        ti.appendChild(tr);
        if (pv.getDevices() == null)
            pv.setDevices(new ArrayList<DeviceMapBean>());
        if (pv.getDevices().isEmpty()) {//如果为空预设对象
            DeviceMapBean dv = new DeviceMapBean();
            dv.setType("ajax");
            pv.getDevices().add(dv);
            dv = new DeviceMapBean();
            dv.setType("mil");
            pv.getDevices().add(dv);
        } else if (pv.getDevices().size() == 1) {//如果只有一个先创建其它类型对象
            DeviceMapBean dv = new DeviceMapBean();
            dv.setType(pv.getDevices().get(0).getType().equals("ajax") ? "mil" : "ajax");
            pv.getDevices().add(dv);
        }
        Treechildren tc = new Treechildren();
        for (DeviceMapBean dv : pv.getDevices()) {
            Treeitem tm = new Treeitem();
            tm.setValue(dv.getType());
            tr = new Treerow();
            Treecell treecell = new Treecell(dv.getType().equals("ajax") ? Labels.getLabel("admin.project.device.ajax") : Labels.getLabel("admin.project.device.phone"));
            treecell.setIconSclass(tm.getValue().equals("ajax") ? "z-icon-laptop h5" : "z-icon-tablet h5");
            treecell.setSpan(3);
            tr.appendChild(treecell);
            tm.appendChild(tr);
            tc.appendChild(tm);
        }
        ti.appendChild(tc);
        tree.getTreechildren().appendChild(ti);
        return ti;
    }

    //创建新门户文件夹
    private void createFolder(String pathName) {
        FileUtil.mkdirForNoExists(new AppServiceFileUtils().getFilePath(pathName,TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN));
        FileUtil.mkdirForNoExists(new AppServiceFileUtils().getFilePath(pathName,TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN));
        FileUtil.mkdirForNoExists(new AppServiceFileUtils().getFilePath(pathName,TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_LOGIN));
        FileUtil.mkdirForNoExists(new AppServiceFileUtils().getFilePath(pathName,TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_MAIN));
        FileUtil.mkdirForNoExists(new AppServiceFileUtils().getHisFilePath(pathName,TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN));
        FileUtil.mkdirForNoExists(new AppServiceFileUtils().getHisFilePath(pathName,TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN));
        FileUtil.mkdirForNoExists(new AppServiceFileUtils().getHisFilePath(pathName,TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_LOGIN));
        FileUtil.mkdirForNoExists(new AppServiceFileUtils().getHisFilePath(pathName,TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_MAIN));
    }

    //树选中事件
    private void selectedItem(){
        template_save.setDisabled(false);
        unSaveLimit(false);
        if(loginSaveFlag||mainSaveFlag){
            WebUtils.showConfirm(Labels.getLabel("button.save"), new EventListener<Event>() {
                public void onEvent(Event event) throws Exception {
                    if (event.getName().equals(Events.ON_OK)) {
                        save();
                    }else {
                        String pathName =null;
                        if("default".equals(name.getValue())){
                            pathName = "";
                        }else{
                            pathName = name.getValue();
                        }
                        if(loginSaveFlag){
                            String pathLogin = StudioApp.getServletContext().getRealPath(new TemplateUtil().getFilePath(pathName, template_login));
                            String hisPathLogin = StudioApp.getServletContext().getRealPath(new TemplateUtil().getHisFilePath(pathName, template_login));
                            try {
                                FileUtil.copyDir(hisPathLogin,pathLogin);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            FileUtil.delAllFile(hisPathLogin);
                        }else if(mainSaveFlag){
                            String pathMain = StudioApp.getServletContext().getRealPath(new TemplateUtil().getFilePath(pathName, template_main));
                            String hisPathMain = StudioApp.getServletContext().getRealPath(new TemplateUtil().getHisFilePath(pathName, template_main));
                            try {
                                FileUtil.copyDir(hisPathMain,pathMain);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            FileUtil.delAllFile(hisPathMain);
                        }
                    }
                    mainSaveFlag = false;
                    loginSaveFlag = false;
                    showPortlet();
                }
            });
        }else{
            showPortlet();
        }
    }

    private void showPortlet(){
        updateFlag = false;
        Treeitem sel = tree.getSelectedItem();
        if (laptopLoginPage.getFirstChild() != null)
            laptopLoginPage.getFirstChild().detach();
        if (laptopMainPage.getFirstChild() != null)
            laptopMainPage.getFirstChild().detach();
        if (mobileLoginPage.getFirstChild() != null)
            mobileLoginPage.getFirstChild().detach();
        if (mobileMainPage.getFirstChild() != null)
            mobileMainPage.getFirstChild().detach();
        if("default".equals(sel.getParentItem().getValue())){
            name.setValue("default");
            name.setDisabled(true);
            desc.setValue(Labels.getLabel("admin.project.default.portlet"));
            desc.setDisabled(true);
            query.setValue("");
            query.setDisabled(true);
            prompt.setVisible(false);
            fileImport_laptop_login.setDisabled(false);
            fileImport_laptop_main.setDisabled(false);
            fileImport_mobile_login.setDisabled(false);
            fileImport_mobile_main.setDisabled(false);
            if (DeviceType.AJAX.getName().equals(sel.getValue())) {
                portlet_type = "laptop";
                template_login = TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN;
                template_main = TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN;
                for(DeviceMapBean dm : Contexts.getProject().getDevices()) {
                    if(DeviceType.AJAX.getName().equals(dm.getType())&&null!=getDevice(dm,template_login)&&null!=getDevice(dm,template_main)){
                        loginXml = updateXml(updateFlag,getDevice(dm,template_login),"",template_login);
                        mainXml = updateXml(updateFlag,getDevice(dm,template_main),"",template_main);
                    }else if(DeviceType.AJAX.getName().equals(dm.getType())){
                        dm.setLoginId(0);
                        dm.setMainId(0);
                        loginXml = null;
                        mainXml = null;
                    }
                }
                laptop_div.setVisible(true);
                mobile_div.setVisible(false);
                redraw(loginXml, laptopLoginPage, "login");
                redraw(mainXml, laptopMainPage, "main");
            } else {
                portlet_type = "mobile";
                template_login = TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_LOGIN;
                template_main = TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_MAIN;
                for(DeviceMapBean dm :Contexts.getProject().getDevices()){
                    if(DeviceType.MOBILE.getName().equals(dm.getType())&&null!=getDevice(dm,template_login)&&null!=getDevice(dm,template_main)){
                        loginXml = updateXml(updateFlag,getDevice(dm,template_login),"",template_login);
                        mainXml = updateXml(updateFlag,getDevice(dm,template_main),"",template_main);
                    }else if(DeviceType.MOBILE.getName().equals(dm.getType())){
                        dm.setLoginId(0);
                        dm.setMainId(0);
                        loginXml = null;
                        mainXml = null;
                    }

                }
                laptop_div.setVisible(false);
                mobile_div.setVisible(true);
                Clients.evalJavaScript("setBGImage('" + mainBgImage.getUuid() + "','" + mobileLoginDiv.getUuid() + "')");
                Clients.evalJavaScript("setBGImage('" + loginBgImage.getUuid() + "','" + mobileMainDiv.getUuid() + "')");
                redraw(loginXml, mobileLoginPage, "login");
                redraw(mainXml,mobileMainPage, "main");
            }
        }else{
            PortletBean pb = sel.getParentItem().getValue();
            index = Contexts.getProject().getPortlets().indexOf(pb);
            if (null != pb.getName()&&!"".equals(pb.getName())) {
                name.setValue(pb.getName());
                desc.setValue(pb.getDesp());
                query.setValue(pb.getOnInitQuery());
                name.setDisabled(true);
                prompt.setVisible(false);
                desc.setDisabled(false);
                query.setDisabled(false);
                fileImport_laptop_login.setDisabled(false);
                fileImport_laptop_main.setDisabled(false);
                fileImport_mobile_login.setDisabled(false);
                fileImport_mobile_main.setDisabled(false);
                if (DeviceType.AJAX.getName().equals(sel.getValue())) {
                    portlet_type = "laptop";
                    template_login = TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN;
                    template_main = TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN;
                    for(DeviceMapBean dm :pb.getDevices()) {
                        if(DeviceType.AJAX.getName().equals(dm.getType())&&null!=getDevice(dm,template_login)&&null!=getDevice(dm,template_main)){
                            loginXml = updateXml(updateFlag,getDevice(dm,template_login),pb.getName(),template_login);
                            mainXml = updateXml(updateFlag,getDevice(dm,template_main),pb.getName(),template_main);
                        }else if(DeviceType.AJAX.getName().equals(dm.getType())){
                            dm.setLoginId(0);
                            dm.setMainId(0);
                            loginXml = null;
                            mainXml = null;
                        }
                    }
                    laptop_div.setVisible(true);
                    mobile_div.setVisible(false);
                    redraw(loginXml, laptopLoginPage, "login");
                    redraw(mainXml, laptopMainPage, "main");
                } else {
                    portlet_type = "mobile";
                    template_login = TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_LOGIN;
                    template_main = TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_MAIN;
                    for(DeviceMapBean dm :pb.getDevices()){
                        if(DeviceType.MOBILE.getName().equals(dm.getType())&&null!=getDevice(dm,template_login)&&null!=getDevice(dm,template_main)){
                            loginXml = updateXml(updateFlag,getDevice(dm,template_login),pb.getName(),template_login);
                            mainXml = updateXml(updateFlag,getDevice(dm,template_main),pb.getName(),template_main);
                        }else if(DeviceType.MOBILE.getName().equals(dm.getType())){
                            dm.setLoginId(0);
                            dm.setMainId(0);
                            loginXml = null;
                            mainXml = null;
                        }
                    }
                    laptop_div.setVisible(false);
                    mobile_div.setVisible(true);
                    Clients.evalJavaScript("setBGImage('" + mainBgImage.getUuid() + "','" + mobileLoginDiv.getUuid() + "')");
                    Clients.evalJavaScript("setBGImage('" + loginBgImage.getUuid() + "','" + mobileMainDiv.getUuid() + "')");
                    redraw(loginXml, mobileLoginPage, "login");
                    redraw(mainXml,mobileMainPage, "main");
                }
            } else {
                name.setValue("");
                desc.setValue("");
                query.setValue("");
                loginXml = null;
                mainXml = null;
                name.setDisabled(false);
                prompt.setVisible(true);
                desc.setDisabled(false);
                query.setDisabled(false);
                laptopLoginPage.setSrc(null);
                laptopMainPage.setSrc(null);
                mobileLoginPage.setSrc(null);
                mobileMainPage.setSrc(null);
                unSaveLimit(true);
                if (DeviceType.AJAX.getName().equals(sel.getValue())) {
                    laptop_div.setVisible(true);
                    mobile_div.setVisible(false);
                }else{
                    laptop_div.setVisible(false);
                    mobile_div.setVisible(true);
                }
            }
        }
    }

    //删除门户
    private void onDelete(final Event evt) {
        WebUtils.showConfirm(Labels.getLabel("button.delete"), new EventListener<Event>() {
            public void onEvent(Event event) throws Exception {
                if (event.getName().equals(Events.ON_OK)) {
                    Treeitem sel = (Treeitem) evt.getTarget().getParent().getParent().getParent();
                    PortletBean pv = sel.getValue();
                    for(DeviceMapBean dm :pv.getDevices()) {
                        if (DeviceType.AJAX.getName().equals(dm.getType())) {
                            if(dm.getLoginId()!=0){
                                StudioApp.execute(new deleteDeviceCmd(dm.getLoginId()));
                            }
                            if(dm.getMainId()!=0) {
                                StudioApp.execute(new deleteDeviceCmd(dm.getMainId()));
                            }
                        }else{
                            if(dm.getLoginId()!=0){
                                StudioApp.execute(new deleteDeviceCmd(dm.getLoginId()));
                            }
                            if(dm.getMainId()!=0) {
                                StudioApp.execute(new deleteDeviceCmd(dm.getMainId()));
                            }
                        }
                    }
                    Contexts.getProject().getPortlets().remove(pv);
                    StudioApp.execute(new UpdateProjectCmd());
                    FileUtil.delAllFile(new AppServiceFileUtils().getFilePath(pv.getName(),TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN));
                    FileUtil.delAllFile(new AppServiceFileUtils().getFilePath(pv.getName(),TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN));
                    FileUtil.delAllFile(new AppServiceFileUtils().getFilePath(pv.getName(),TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_LOGIN));
                    FileUtil.delAllFile(new AppServiceFileUtils().getFilePath(pv.getName(),TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_MAIN));
                    sel.detach();
                    template_save.setDisabled(true);
                }
            }
        });
    }

    //解析渲染xml
    private void redraw(String xml, Iframe name, String str) {
        if (!Strings.isBlank(xml)) {
            StringBuilder sb = new StringBuilder();
            sb.append("<?taglib uri=\"http://www.zkoss.org/dsp/web/core\" prefix=\"c\"?>\n");
            sb.append(xml);
            xml = sb.toString();
            try {
                CodeFormatter.formatXML(ZulXsdUtil.buildDocument(xml));
                name.getDesktop().getSession().setAttribute(str, xml);
                name.getDesktop().getSession().setAttribute("projectName", Contexts.getProject().getId());
                String srcPath = "/richlet/dyamic?s=" + System.currentTimeMillis() + "&compose=" + str ;
                name.setSrc(srcPath);
                editMsg.setValue("");
            } catch (Exception ex) {
                msg = ex.getMessage();
                if (msg != null) {
                    int idx = msg.indexOf("for class");
                    if (idx > 0) {
                        msg = msg.substring(0, idx);
                    } else if ((idx = msg.indexOf("SAXParseException;")) >= 0) {
                        msg = msg.substring(idx + 18);
                    }
                } else {
                    msg = "Wrong page content";
                }
                editMsg.setValue((Labels.getLabel("admin.project.portlet.msg"))+"："+""+msg);
            }
        } else {
            name.setSrc(null);
        }
    }

    private void unSaveLimit(boolean saveflag){
        fileImport_laptop_login.setDisabled(saveflag);
        fileImport_laptop_main.setDisabled(saveflag);
        fileImport_mobile_login.setDisabled(saveflag);
        fileImport_mobile_main.setDisabled(saveflag);
        imageImport_laptop_login.setDisabled(saveflag);
        chooseTemp_laptop_login.setDisabled(saveflag);
        fileImport_laptop_login.setDisabled(saveflag);
        imageImport_laptop_main.setDisabled(saveflag);
        chooseTemp_laptop_main.setDisabled(saveflag);
        fileImport_laptop_main.setDisabled(saveflag);
        edit_laptop_login.setDisabled(saveflag);
        edit_laptop_main.setDisabled(saveflag);
        imageImport_mobile_login.setDisabled(saveflag);
        chooseTemp_mobile_login.setDisabled(saveflag);
        fileImport_mobile_login.setDisabled(saveflag);
        imageImport_mobile_main.setDisabled(saveflag);
        chooseTemp_mobile_main.setDisabled(saveflag);
        fileImport_mobile_main.setDisabled(saveflag);
        edit_mobile_login.setDisabled(saveflag);
        edit_mobile_main.setDisabled(saveflag);
    }

    //图片导入
    private void imageImport(Event evt, final TemplateUtil.TemplateType tle) {
        String pathName =null;
        String replacePath = null;
        if("default".equals(name.getValue())){
            pathName = "";
        }else{
            pathName = name.getValue();
        }
        List<String> pathList = FileUtil.getFilePathWithDirectory(new AppServiceFileUtils().getFilePath(pathName,tle)+"/img");

        if (pathList != null && pathList.size() > 0) {
            AbstractView.createAppPageImageView(new EditorCallback<String>() {
                @Override
                public String getValue() {
                    return null;
                }

                @Override
                public void setValue(String value) {
                    if (tle == TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN ) {
                        redraw(loginXml,laptopLoginPage, "login");
                    } else if(tle == TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_LOGIN) {
                        redraw(loginXml,mobileLoginPage, "login");
                    } else if(tle == TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN) {
                        redraw(mainXml,laptopMainPage, "main");
                    } else {
                        redraw(mainXml,mobileMainPage, "main");
                    }
                }

                @Override
                public String getTitle() {
                    return Labels.getLabel("editor.template.image.import");
                }

                @Override
                public Page getPage() {
                    if (tle == TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN || tle == TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN) {
                        return laptopLoginPage.getPage();
                    } else {
                        return mobileLoginPage.getPage();
                    }
            }

                @Override
                public Editor getEditor() {
                    return null;
                }
            }, pathName, tle, evt.getTarget()).doOverlapped();
        } else
            WebUtils.showInfo(Labels.getLabel("editor.noImage.error"));
    }

    private void setContent(String path, TemplateUtil.TemplateType ttlt) {
        String xml = null;
        xml = getZulcode(path);
        String pathName =null;
        String replacePath = null;
        if("default".equals(name.getValue())){
            pathName = "";
        }else{
            pathName = name.getValue();
        }
        if (ttlt == TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN) {
            replacePath =pathName+"d0";
        }
        if (ttlt == TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN) {
            replacePath =pathName+"d1";
        }
        if (ttlt == TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_LOGIN) {
            replacePath =pathName+ "m0";
        }
        if (ttlt == TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_MAIN) {
            replacePath =pathName+ "m1";
        }
        xml = xml.replaceAll("#\\{708\\}", replacePath);
        if (ttlt == TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN ) {
            loginXml = xml;
            redraw(loginXml,laptopLoginPage, "login");
        } else if(ttlt == TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_LOGIN) {
            loginXml = xml;
            redraw(loginXml,mobileLoginPage, "login");
        } else if(ttlt == TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN) {
            mainXml = xml;
            redraw(mainXml,laptopMainPage, "main");
        } else {
            mainXml = xml;
            redraw(mainXml,mobileMainPage, "main");
        }
    }

    //修改xml引用地址
    private String updateXml(boolean flag,String xml,String portletsName,TemplateUtil.TemplateType ttlt){

        String str = null;
        if (ttlt == TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN) {
            str = "d0";
        }
        if (ttlt == TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_MAIN) {
            str = "d1";
        }
        if (ttlt == TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_LOGIN) {
            str = "m0";
        }
        if (ttlt == TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_MAIN) {
            str = "m1";
        }
        if("default".equals(portletsName)||flag){
            xml = xml.replaceAll("#\\{708\\}", str);
            xml = xml.replaceAll(portletsName+str, str);
        }else{
            xml = xml.replaceAll(str, portletsName+str);
        }
        return xml;
    }


    private String getZulcode(String path) {
        if (path != null) {
            String xml = "";
            try {
                InputStream inputStream = new FileInputStream(new File(path));
                xml = IOUtils.toString(inputStream, "UTF-8");
                xml = xml.replaceAll("\uFEFF", "");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return xml;
        }
        return "";
    }

    //文件导入
    private void setfileImport(Event evt) {
        UploadEvent ue = (UploadEvent) evt;
        byte[] data = ue.getMedia().getByteData();
        SimpleDateFormat time = new SimpleDateFormat("yyyyMMddHHmmss");
        FileUtil.mkdirForNoExists(new AppServiceFileUtils().getJarFilePath());
        String zipPath = new AppServiceFileUtils().getJarFilePath()+ "/" +Contexts.getUser().getUserId()+"_"+time.format(new Date())+"_"+ue.getMedia().getName();
        if(FileUtil.setBytesWithFile(data, zipPath)) {
            WebUtils.showSuccess(Labels.getLabel("editor.template.store.export"));
        }else{
            WebUtils.showError(Labels.getLabel("message.error", new String[]{Labels.getLabel("button.import")}));
        }
    }

    private String getDevice(DeviceMapBean dm ,TemplateUtil.TemplateType type){
        String xml = null;

        if (type == TemplateUtil.TemplateType.TEMPLATE_TYPE_DESKTOP_LOGIN || type == TemplateUtil.TemplateType.TEMPLATE_TYPE_MOBILE_LOGIN) {
            if(null != dm.getLoginPage()&&!"".equals(dm.getLoginPage())){
                xml = dm.getLoginPage();
            }else{
                if(dm.getLoginId()!=0){
                    xml = StudioApp.execute(new GetPageXmlCmd(dm.getLoginId()));
                }else{
                    return null;
                }
            }
        } else {
            if(null != dm.getMainPage()&&!"".equals(dm.getMainPage())){
                xml = dm.getMainPage();
            }else{
                if(dm.getMainId()!=0){
                    xml = StudioApp.execute(new GetPageXmlCmd(dm.getMainId()));
                }else{
                    return null;
                }
            }
        }
        return xml;
    }

    private void  saveDevice(DeviceMapBean dm,String loginxml,String mainXml){
        if(dm.getLoginId()!=0){
            StudioApp.execute(new UpdateDeviceCmd(dm.getLoginId(),loginxml));
        }else{
            Long loginId=StudioApp.execute(new AddDeviceCmd(loginxml));
            dm.setLoginId(loginId);
            dm.setLoginPage("");
        }
        if(dm.getMainId()!=0){
            StudioApp.execute(new UpdateDeviceCmd(dm.getMainId(),mainXml));
        }else{
            Long mainId=StudioApp.execute(new AddDeviceCmd(mainXml));
            dm.setMainId(mainId);
            dm.setMainPage("");
        }
    }

    @Override
    public boolean isDirty() {
        return false;
    }

    @Override
    public boolean save() {
        updateFlag = true;
        prompt.setVisible(false);
        name.setDisabled(true);
        unSaveLimit(false);
        if (null != loginXml && !"".equals(loginXml.trim())) {
            loginXml = loginXml.replace("<?taglib uri=\"http://www.zkoss.org/dsp/web/core\" prefix=\"c\"?>\n", "");
            loginXml = updateXml(updateFlag, loginXml, name.getValue(), template_login);
        }
        if(null != mainXml&&!"".equals(mainXml.trim())) {
            mainXml = mainXml.replace("<?taglib uri=\"http://www.zkoss.org/dsp/web/core\" prefix=\"c\"?>\n", "");
            mainXml = updateXml(updateFlag, mainXml, name.getValue(), template_main);
        }
        if ("default".equals(name.getValue())) {
            for (DeviceMapBean dm : Contexts.getProject().getDevices()) {
                if ("laptop".equals(portlet_type) && dm.getType().equals(DeviceType.AJAX.getName())) {
                    saveDevice(dm,loginXml,mainXml);
                } else if("mobile".equals(portlet_type)&& dm.getType().equals(DeviceType.MOBILE.getName())) {
                    saveDevice(dm,loginXml,mainXml);
                }
            }
        }else {
            createFolder(name.getValue());
            ((Treecell) tree.getSelectedItem().getParentItem().getTreerow().getFirstChild()).setLabel(name.getValue());
            PortletBean updatePortlet = Contexts.getProject().getPortlets().get(index);
            updatePortlet.setName(name.getValue());
            updatePortlet.setDesp(desc.getValue());
            updatePortlet.setOnInitQuery(query.getValue());
                if ("laptop".equals(portlet_type)) {
                    for (DeviceMapBean db : updatePortlet.getDevices()) {
                        if (db.getType().equals(DeviceType.AJAX.getName())) {
                            saveDevice(db,loginXml,mainXml);
                        }
                    }
                } else {
                    for (DeviceMapBean db : updatePortlet.getDevices()) {
                        if (db.getType().equals(DeviceType.MOBILE.getName())) {
                            saveDevice(db,loginXml,mainXml);
                        }
                    }
                }
            }
        if (StudioApp.execute(new UpdateProjectCmd())) {
            loginSaveFlag = false;
            mainSaveFlag = false;
            return true;
        }
        return false;
    }

}





